import os

import requests
from lxml import etree

# 下载4k美女图片
if __name__ == "__main__":
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36',
    }
    # "http://pic.netbian.com/4kmeinv/index_2.html"
    url = "http://pic.netbian.com/4kmeinv/index_"

    for num in range(15, 161):
        print("下载页数：" + str(num))
        url_page = url + str(num) + ".html"
        page_text = requests.get(url=url_page, headers=headers).text
        # 解决中文乱码
        page_text = page_text.encode('iso-8859-1').decode('gbk')

        tree = etree.HTML(page_text)
        li_list = tree.xpath('//div[@class="slist"]/ul/li')
        baseUrl = 'http://pic.netbian.com'

        # 创建图片文件夹
        imp_dl_path = "./meinv_pic"
        if not os.path.exists(imp_dl_path):
            os.mkdir(imp_dl_path)

        for li in li_list:
            # 图片详情页面的URL
            img_detail_url = baseUrl + li.xpath('./a/@href')[0]
            # img_name = li.xpath('./a/b/text()')[0] + ".jpg"
            img_name = li.xpath('./a/img/@alt')[0] + ".jpg"
            print(img_detail_url, img_name)

            # 请求图片详情页
            page_text = requests.get(url=img_detail_url, headers=headers).text
            tree = etree.HTML(page_text)
            # 图片URL
            img_url = baseUrl + tree.xpath('//div[@class="photo-pic"]/a/img/@src')[0]

            img_r = requests.get(url=img_url, headers=headers)
            print(img_url + " " + str(img_r.status_code))
            # requests的content表示HTTP响应的二进制数据内容，即图片数据
            img_data = img_r.content

            img_path = "meinv_pic/" + img_name
            # 将图片数据写入文件
            with open(img_path, 'wb') as fp:
                fp.write(img_data)
                print(img_name + " download ok")
